package hn.cch.springboot_redisson.redisson;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class RedissonValue {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.database}")
    private int database;

    @Bean
    public RedissonClient redissonClient(){
    // public RedissonClient singleServerRedissonClient(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port);
        if (StringUtils.isEmpty(password)){
            config.useSingleServer().setPassword(null);
        } else {
            config.useSingleServer().setPassword(password);
        }
        config.useSingleServer().setDatabase(database);
        return Redisson.create(config);
    }

    // @Bean
    public RedissonClient clusterServersRedissonClient(){
        String nodeAddress = "redis://" + host + ":" + port;

        Config config = new Config();
        config.useClusterServers().setScanInterval(1000);
        config.useClusterServers().addNodeAddress(nodeAddress);
        if (StringUtils.isEmpty(password)){
            config.useClusterServers().setPassword(null);
        } else {
            config.useClusterServers().setPassword(password);
        }
        return Redisson.create(config);
    }

    // @Bean
    public RedissonClient masterSlaveServersRedissonClient(){
        String masterAddress = "redis://" + host + ":" + port;
        String[] slaveAddress = new String[]{"", ""};

        Config config = new Config();
        config.useMasterSlaveServers().setMasterAddress(masterAddress);
        config.useMasterSlaveServers().addSlaveAddress(slaveAddress);
        if (StringUtils.isEmpty(password)){
            config.useMasterSlaveServers().setPassword(null);
        } else {
            config.useMasterSlaveServers().setPassword(password);
        }
        config.useMasterSlaveServers().setDatabase(database);
        return Redisson.create(config);
    }


}
